import React, { useState, useEffect } from 'react';
import { message, Spin, Alert } from 'antd';
import { 
    DubboOverviewDTO, 
    DubboProviderDTO, 
    DubboConsumerDTO,
    getDubboOverview 
} from '../../../services/dubboAnalysis';
import { getUnit } from '../../../services/unit';
import DubboOverviewCards from './DubboOverviewCards';
import DubboProviderTable from './DubboProviderTable';
import DubboConsumerTable from './DubboConsumerTable';
import ReferenceDetailDrawer from './ReferenceDetailDrawer';
import ProviderDetailDrawer from './ProviderDetailDrawer';

interface DubboAnalysisTabProps {
    unitId: string;
}

const DubboAnalysisTab: React.FC<DubboAnalysisTabProps> = ({ unitId }) => {
    // 概览数据状态
    const [overview, setOverview] = useState<DubboOverviewDTO | undefined>(undefined);
    const [overviewLoading, setOverviewLoading] = useState<boolean>(false);
    const [overviewError, setOverviewError] = useState<string | null>(null);
    
    // 单元信息状态（用于获取 Git 仓库信息）
    const [unitInfo, setUnitInfo] = useState<any>(null);

    // 引用详情抽屉状态
    const [referenceDrawerVisible, setReferenceDrawerVisible] = useState<boolean>(false);
    const [selectedProvider, setSelectedProvider] = useState<DubboProviderDTO | null>(null);

    // 提供者详情抽屉状态
    const [providerDrawerVisible, setProviderDrawerVisible] = useState<boolean>(false);
    const [selectedConsumer, setSelectedConsumer] = useState<DubboConsumerDTO | null>(null);

    // 加载概览数据
    const loadOverview = async () => {
        setOverviewLoading(true);
        setOverviewError(null);
        try {
            const data = await getDubboOverview(unitId);
            setOverview(data);
        } catch (error: any) {
            const errorMsg = error.message || '加载 Dubbo 服务概览失败';
            setOverviewError(errorMsg);
            message.error(errorMsg);
            setOverview(undefined);
        } finally {
            setOverviewLoading(false);
        }
    };

    // 加载单元信息
    const loadUnitInfo = async () => {
        try {
            const response = await getUnit(unitId);
            const data = (response && response.data) ? response.data : response;
            setUnitInfo(data || null);
        } catch (error: any) {
            console.error('加载单元信息失败:', error);
            setUnitInfo(null);
        }
    };

    // 初始加载概览数据和单元信息
    useEffect(() => {
        if (unitId) {
            loadOverview();
            loadUnitInfo();
        }
    }, [unitId]);

    // 处理查看引用详情
    const handleViewReferences = (provider: DubboProviderDTO) => {
        setSelectedProvider(provider);
        setReferenceDrawerVisible(true);
    };

    // 处理关闭引用详情抽屉
    const handleCloseReferenceDrawer = () => {
        setReferenceDrawerVisible(false);
        setSelectedProvider(null);
    };

    // 处理查看提供者详情
    const handleViewProviderDetail = (consumer: DubboConsumerDTO) => {
        setSelectedConsumer(consumer);
        setProviderDrawerVisible(true);
    };

    // 处理关闭提供者详情抽屉
    const handleCloseProviderDrawer = () => {
        setProviderDrawerVisible(false);
        setSelectedConsumer(null);
    };

    return (
        <div style={{ 
            padding: '24px',
            background: '#f5f5f5',
            minHeight: 'calc(100vh - 200px)'
        }}>
            {/* 页面标题 */}
            <div style={{
                fontSize: '24px',
                fontWeight: '600',
                color: '#333',
                marginBottom: '24px',
                display: 'flex',
                alignItems: 'center'
            }}>
                <span style={{ 
                    display: 'inline-block',
                    width: '5px',
                    height: '24px',
                    background: '#1890ff',
                    marginRight: '12px',
                    borderRadius: '3px'
                }} />
                Dubbo 依赖分析
            </div>

            {/* 错误提示 */}
            {overviewError && (
                <Alert
                    message="加载失败"
                    description={overviewError}
                    type="error"
                    showIcon
                    closable
                    onClose={() => setOverviewError(null)}
                    style={{ marginBottom: '24px' }}
                />
            )}

            {/* 加载状态 */}
            {overviewLoading && !overview ? (
                <div style={{
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    minHeight: '400px'
                }}>
                    <Spin size="large" tip="加载 Dubbo 服务数据中..." />
                </div>
            ) : (
                <>
                    {/* 概览卡片 */}
                    <DubboOverviewCards 
                        overview={overview} 
                        loading={overviewLoading} 
                    />

                    {/* 只有在有配置的情况下才显示表格 */}
                    {overview && overview.hasConfig && (
                        <>
                            {/* Provider 服务列表 */}
                            <DubboProviderTable
                                unitId={unitId}
                                unitInfo={unitInfo}
                                onViewReferences={handleViewReferences}
                            />

                            {/* Consumer 服务列表 */}
                            <DubboConsumerTable
                                unitId={unitId}
                                onViewProviderDetail={handleViewProviderDetail}
                            />
                        </>
                    )}
                </>
            )}

            {/* 引用详情抽屉 */}
            <ReferenceDetailDrawer
                visible={referenceDrawerVisible}
                provider={selectedProvider}
                onClose={handleCloseReferenceDrawer}
            />

            {/* 提供者详情抽屉 */}
            <ProviderDetailDrawer
                visible={providerDrawerVisible}
                unitId={unitId}
                consumer={selectedConsumer}
                onClose={handleCloseProviderDrawer}
            />
        </div>
    );
};

export default DubboAnalysisTab;
